const { sqlPromise } = require("../db/sqlPromise");
//导入解析formdata格式表单数据的包
const multer = require("multer");
//导入处理路径的核心模块
const path = require("path");
// 创建multer的实例对象,通过dest属性指定文件的存放路径
const upload = multer({ dest: path.join(__dirname, "../uploads") });
// 发布新文章
// 1. 初始化路由模块
// 2. 初始化路由处理函数模块
// 3. 使用 multer 解析表单数据
// 4. 验证表单数据
// 5. 实现发布文章的功能
exports.addArticle = async (req, res) => {
  //   console.log(req.body);
  if (!req.file || req.file.fieldname !== "cover_img")
    return res.send({ status: 1, message: "文章封面是必选参数" });
  const articleInfo = {
    // 标题、内容、状态、所属的分类Id
    ...req.body,
    // 文章封面在服务器端的存放路径
    cover_img: path.join("./uploads", req.file.filename),
    // 文章发布时间
    pub_date: new Date(),
    // 文章作者的Id
    author_id: req.user.id,
  };
  let sql = "insert into ev_articles set ?";
  let results = await sqlPromise(sql, articleInfo);
  if (results.affectedRows != 1)
    return res.send({ status: 1, message: "发布文章失败" });
  res.send({ status: 0, message: "发布文章成功" });
};
// 获取文章列表数据
exports.getArticleList = async (req, res) => {
  // 后端解决方案
  // 联表查询
  // let sql =
  //   "select arcs.id,arcs.title,arcs.pub_date,arcs.state,cate.name  from ev_articles  arcs left join ev_article_cate cate on arcs.cate_id=cate.Id";
  // 前端解决方案1
  // let sql1 = "select * from ev_articles";
  // let res1 = await sqlPromise(sql1);
  // let sql2 = "select * from ev_article_cate";
  // let res2 = await sqlPromise(sql2);
  // let data1 = res1.reduce((preVal, curVal) => {
  //   let { id, title, pub_date, state, cate_id } = curVal;
  //   preVal.push({ id, title, pub_date, state, cate_id });
  //   return [...preVal];
  // }, []);
  // let results = data1.reduce((preVal, curVal) => {
  //   let data2 = res2.reduce((pre, cur) => {
  //     if (cur.Id == curVal.cate_id) {
  //       curVal["cate_name"] = cur.name;
  //       delete curVal.cate_id;
  //     }
  //     return curVal;
  //   }, curVal);
  //   preVal.push(data2);
  //   return [...preVal];
  // }, []);
  // res.send(results);
  // 前端解决方案2
  // let sql1 = "select * from ev_articles";
  // let res1 = await sqlPromise(sql1);
  // let sql2 = "select * from ev_article_cate";
  // let res2 = await sqlPromise(sql2);
  // let data = res1.reduce((preVal, curVal, index) => {
  //   let { id, title, pub_data, state } = curVal;
  //   let [{ name: cate_name }] = res2.filter((item) => {
  //     if (item.Id == curVal.cate_id) return item;
  //   });
  //   preVal[index] = { id, title, pub_data, state, cate_name };
  //   return preVal;
  // }, []);
  // res.send(data);

  let sql;
  let results;
  if (req.body.cate_id && req.body.state) {
    sql = "select * from ev_articles where cate_id=? and state=?";
    results = await sqlPromise(sql, [req.body.cate_id, req.body.state]);
  } else if (req.body.cate_id) {
    sql = "select * from ev_articles where cate_id=?";
    results = await sqlPromise(sql, [req.body.cate_id]);
  } else if (req.body.state) {
    sql = "select * from ev_articles where state=?";
    results = await sqlPromise(sql, [req.body.state]);
  } else {
    sql = "select * from ev_articles";
    results = await sqlPromise(sql, [req.body.pagenum, req.body.pagesize]);
  }
  if (!results.length)
    return res.send({ status: 1, message: "获取文章数据列表失败" });
  let sql2 = "select * from ev_article_cate";
  let cateRes = await sqlPromise(sql2);
  let dataRes = results.reduce((preVal, curVal, index) => {
    let { id, title, pub_data, state } = curVal;
    let [{ name: cate_name }] = cateRes.filter((item) => {
      if (item.Id === curVal.cate_id) return item;
    });
    preVal[index] = { id, title, pub_data, state, cate_name };
    return preVal;
  }, []);
  let data = [];
  if (dataRes.length <= req.body.pagesize) {
    data = dataRes;
  } else {
    for (let i = 0, j = dataRes.length; i < j; i += req.body.pagesize) {
      data.push(dataRes.slice(i, i + req.body.pagesize));
    }
    data = data[req.body.pagenum - 1];
  }
  res.send({
    status: 0,
    message: "获取文章列表成功",
    data: data,
    total: results.length,
  });
};
// 根据id删除文章数据
exports.delArticle = async (req, res) => {
  let sql = "delete from ev_articles where id=?";
  let results = await sqlPromise(sql, req.params.id);
  if (results.affectedRows != 1)
    return res.send({ status: 1, message: "删除文章失败" });
  res.send({ status: 0, message: "删除文章成功" });
};
// 根据id获取文章详情
exports.getArticle = async (req, res) => {
  let sql = "select * from ev_articles where id=?";
  let results = await sqlPromise(sql, req.params.id);
  if (!results.length)
    return res.send({ status: 1, message: "获取文章详情失败" });
  results[0].cover_img = path.join(__dirname, "../", results[0].cover_img);
  res.send({ status: 0, message: "获取文章详情成功", data: results[0] });
};
// 根据id更新文章信息
exports.updateArticle = async (req, res) => {
  let sql = "update ev_articles set ? where id=?";
  const articleInfo = {
    // 标题、内容、状态、所属的分类Id
    ...req.body,
    // 文章封面在服务器端的存放路径
    cover_img: path.join("/uploads", req.file.filename),
    // 文章发布时间
    pub_date: new Date(),
    // 文章作者的Id
    author_id: req.user.id,
  };
  let results = await sqlPromise(sql, [articleInfo, req.body.id]);
  if (results.affectedRows != 1)
    return res.send({ status: 0, message: "更新文章信息失败" });
  res.send({ status: 0, message: "更新文章信息成功" });
};
